import React from 'react';
import { Breadcrumb, Icon, Popover } from 'antd';
import { WeaLocaleProvider, WeaTools } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

import './style/';
import SearchRcmd from './SearchRcmd';

class Index extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [{
                module: '',
                name: getLabel(33675, '前端菜单'),
                data: [],
            }],
            index: 0,
            rcmdVisible: false,
            rcmdData: [],
        };
        this.setShowData = this.setShowData.bind(this);
        this.getShowData = this.getShowData.bind(this);
        this.onOpen = this.onOpen.bind(this);
        this.onRcmdSearch = this.onRcmdSearch.bind(this);
        this.onRcmdVisibleChange = this.onRcmdVisibleChange.bind(this);
    }

    componentWillMount() {
        WeaTools.callApi('/api/portal/menu/getFrontEndMenu?withPortal=0&isLoadAll=1', 'GET', {}).then((result) => {
            const { data = [] } = result;
            this.setState({
                data: [{
                    module: '',
                    name: getLabel(33675, '前端菜单'),
                    data,
                }],
                index: 0,
            });
        });
    }

    render() {
        const { data, index, rcmdVisible, rcmdData } = this.state;

        return (
            <div className="portal-em-menu">
                <div className="portal-em-menu-toolbar">
                    <div className="portal-em-menu-back" title={getLabel(500304, '上一级')} onClick={() => this.getShowData(index - 1)}>
                        <img src="/spa/portal/images/em/back.png" alt="" />
                    </div>
                    <div className="portal-em-menu-nav">
                        <Breadcrumb ecId={`${this && this.props && this.props.ecId || ''}_Breadcrumb@qah6dc`} separator={<i className="icon-coms-organization-right" />}>
                            {
                                data.map((item, index) => (
                                        <Breadcrumb.Item ecId={`${this && this.props && this.props.ecId || ''}_Breadcrumb.Item@ywk38n@${index}`} key={index} onClick={() => item.data && item.data.length && this.getShowData(index)}>
                                            {index === 0 && <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@0js8dj@${index}`} type="home" />}
                                            <span>{item.name}</span>
                                        </Breadcrumb.Item>
                                    ))
                            }
                        </Breadcrumb>
                    </div>
                    <div className="portal-em-menu-search">
                        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@7gwgtt`}
                          trigger="click"
                          placement="bottomLeft"
                          content={<SearchRcmd ecId={`${this && this.props && this.props.ecId || ''}_SearchRcmd@2biz9k`} data={rcmdData} onOpen={this.onOpen} />}
                          overlayClassName="portal-em-menu-search-rcmd"
                          visible={rcmdVisible}
                          onVisibleChange={this.onRcmdVisibleChange}
                        >
                            <div />
                        </Popover>
                        <input placeholder={getLabel(500305, '请输入菜单名称/首字母')} onClick={this.onRcmdSearch} onChange={this.onRcmdSearch} />
                        <i className="icon-coms-search" />
                    </div>
                </div>
                <div className="portal-em-menu-content">
                    <ul className="portal-em-menu-list">
                        {
                            data[index].data.map((item) => {
                                let IconCom = null;
                                if (item.icon) {
                                    IconCom = <i className={item.icon} />;
                                } else if (index === 0) {
                                        IconCom = <i className={`wevicon-top-menu-default wevicon-top-menu-${item.id}`} />;
                                    } else {
                                        IconCom = <i className={`wevicon wevicon-menu-default wevicon-menu-${item.parentId}-${item.levelid}`} />;
                                    }

                                return (
                                    <li key={item.id} onClick={() => this.setShowData(data[index].module, item, index + 1)}>
                                        <div className={`portal-em-menu-item e9header-top-menu-color${(Math.abs(parseInt(item.id, 10)) & 7)}`}>
                                            {IconCom}
                                        </div>
                                        <span>{item.name}</span>
                                    </li>
                                );
                            })
                        }
                    </ul>
                </div>
            </div>
        );
    }

    setShowData(module, item, index) {
        if (item && item.child && item.child.length) {
            const { data } = this.state;
            data.push({ module: module || item.id, parentId: item.parentId, id: item.id, name: item.name, data: item.child });
            this.setState({ data, index });
        } else if (item) {
                this.onOpen(item);
            }
    }

    getShowData(index) {
        if (index >= 0) {
            const { data } = this.state;
            this.setState({ data: data.slice(0, index + 1), index });
        }
    }

    onOpen(obj, from) {
        if (from === 'search') {
            this.onRcmdVisibleChange(false);
        }

        const url = obj ? obj.fullrouteurl || obj.url : '';

        if (url && url != 'javascript:void(0);') {
            if (window.em && window.em.checkJsApi('openLink')) {
                if (/^(http|https):\/\/([\w.]+\/?)\S*/.test(url)) {
                    window.em.openLink({
                        url,
                        openType: 3,
                    });
                } else {
                    window.em.openLink({
                        url,
                        openType: 3,
                        sysId: window.localStorage.emobile_ec_id,
                    });
                }
            } else {
                window.open(url);
            }
        }
    }

    onRcmdSearch(e) {
        const value = e.target.value;
        this.onRcmdVisibleChange(!!value);

        const { data } = this.state;
        const rcmdData = [];

        const loop = (moduleId, moduleName, item) => {
            const child = item.child;
            if (child && child.length) {
                for (let i = 0, len = child.length; i < len; i++) {
                    const { name = '', pinyin = '' } = child[i];
                    if (name.toLowerCase().indexOf(value.toLowerCase()) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
                        child[i].moduleId = moduleId;
                        child[i].moduleName = moduleName;
                        rcmdData.push(child[i]);
                    }
                    loop(moduleId, moduleName, child[i]);
                }
            }
        };

        data[0].data.forEach((item) => {
            const moduleId = item.infoId || '';
            const moduleName = item.name || '';

            const { name = '', pinyin = '' } = item;
            if (name.toLowerCase().indexOf(value.toLowerCase()) != -1 || pinyin.indexOf(value.toLowerCase()) != -1) {
                item.moduleId = moduleId;
                item.moduleName = moduleId;
            }
            loop(moduleId, moduleName, item);
        });

        this.setState({ rcmdData });
    }

    onRcmdVisibleChange(visible) {
        this.setState({ rcmdVisible: visible });
    }
}

export default Index;
